import Vue from 'vue'
import Router from 'vue-router'
import Layout from '@/components/Layout/';
import store from '../store'

import { getAsyncRoutes } from './asyncRouter';

// // 解决多次点击当前路由报红问题
const originalPush = Router.prototype.push
Router.prototype.push = function push(location) {
    return originalPush.call(this, location).catch(err => err)
}
Vue.use(Router)

// 动态路由
const articleRule = {
    path: '/article',
    name:'文章',
    component: () => import('@/views/article')
}
const userRule = {
    path: '/users',
    name:'用户权限',
    component: () => import('@/views/user'),
}
const nameRule = {
    path: '/home',
    name:'首页',
    component: () => import('@/views/Home'),
}
const noFundRule = {
    path: '*',
    component: () => import('@/views/404')
}

// 路由规则和字符串的映射关系
const ruleMapping = {
    '/article': articleRule,
    '/users': userRule,
    '/home': nameRule,
    '*': noFundRule,
}



// 配置项目中没有涉及权限的公共路由
export const constantRoutes = [
    {
        path: '/login',
        name: '登录',
        component: () => import('@/views/Login'),
        meta: {
            title: "登录", //配置title
        }
    },
    {
        path: '/',
        component: Layout,
        redirect: '/home',
        name:'基本页面',
        children: []
    },
]


const createRouter = () => new Router({
    mode: 'history',
    scrollBehavior: () => ({ y: 0 }),
    routes: constantRoutes
})
const router = createRouter()

export function resetRouter() {
    const newRouter = createRouter()
    router.matcher = newRouter.matcher
}

export function initDynamicRoutes() {
    // 根据二级权限 对路由规则进行动态的添加
    const currentRoutes = router.options.routes
    const rightList = store.getters.addRoutes
    if(rightList.length == 0){
        return
    }
    rightList.forEach(item => { // 如果是没有子路由的话 就直接添加进去 如果有子路由的话就进入二级权限遍历
        console.log(item);
        if (!item.children || item.children.length == 0) {
            const temp = ruleMapping[item.path]
            // 路由规则中添加元数据meta
            currentRoutes[1].children.push(temp)
        }else{
            item.children.forEach(item => {
                // item 二级权限
                const temp = ruleMapping[item.path]
                // 路由规则中添加元数据meta
                currentRoutes[1].children.push(temp)
            })
        }
        constantRoutes.push(noFundRule)
    })


    router.addRoutes(currentRoutes)
}

export default router
